package ad.android.dao.impl;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.dao.DataAccessException;

import ad.android.dao.IApplicationDao;
import ad.android.dao.base.BaseDao;
import ad.android.exception.DaoException;
import ad.android.model.Application;

public class ApplicationDaoHibernateImpl extends BaseDao implements IApplicationDao{

	@Override
	public Application findApplicationByLicenseKey(String key)
			throws DaoException {
		try {
			Session session = getSession();
			String hql = "from Application app where app.licenseKey=:license_key";
			Query query = session.createQuery(hql);
			query.setString("license_key", key);
			Object obj = query.uniqueResult();
			
			if( obj == null){
				return null;
			}
			
			return (Application)obj;
		} catch (HibernateException e) {
			logDebug("findApplicationByLicenseKey",e);
			throw new DaoException(e);
		}
	}

	@Override
	public String findSeckeyByLicenseKey(String licenseKey) throws DaoException {
		try {
			Session session = getSession();
			String hql = "select app.secKey from Application app where app.licenseKey=:license_key";
			Query query = session.createQuery(hql);
			query.setString("license_key", licenseKey);
			Object obj = query.uniqueResult();
			
			if( obj == null){
				return null;
			}
			
			return (String)obj;
		} catch (HibernateException e) {
			logDebug("findSeckeyByLicenseKey",e);
			throw new DaoException(e);
		}
	}

	@Override
	public Application findApplication(Long appId) throws DaoException {
		try {
			return get(Application.class, appId);
		} catch (DataAccessException e) {
			logDebug("findApplication",e);
			throw new DaoException(e);
		}
	}
	
}
